﻿using AutoMapper;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Appointments;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.RisServer.Services.Dtos;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Register;

public class GetExam(IMapper mapper, IRepository<AppointmentPlan, Guid> appointmentPlanRep) : WorkflowBase, IGetExam, ITransientDependency
{
    private readonly IRepository<AppointmentPlan, Guid> _appointmentPlanRep = appointmentPlanRep;
    private readonly IMapper _mapper = mapper;
    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        ExamDto data = null;
        if (input.ContainsKey("Exam") && input.GetValueOrDefault("Exam") is Exam exam)
        {
            //排序
            List<ExamRemark> remarks = exam.ExamRemarks.OrderBy(x => x.CreationTime).ToList();
            List<PatientMatter> patientMatters = exam.PatientMatters.OrderBy(x => x.CreationTime).ToList();
            List<ExamItem> examItems = exam.ExamItems.OrderBy(x => x.CreationTime).ToList();
            List<ExamBodyParty> examBodyParties = exam.ExamBodyParties.OrderBy(x => x.CreationTime).ToList();

            data = _mapper.Map<ExamDto>(exam);
            data.ExamRemarks = _mapper.Map<List<ExamRemakDto>>(remarks);
            data.PatientMatters = _mapper.Map<List<PatientMatterDto>>(patientMatters);
            data.ExamItems = _mapper.Map<List<ExamItemDto>>(examItems);
            data.ExamBodyParties = _mapper.Map<List<ExamBodyPartyDto>>(examBodyParties);

            //检查设备个数，设置form表单[检查设备]显示隐藏使用
            data.DeviceCount = exam.Department.GetDevices().Where(d => d.DeviceType.Oid == data.DeviceType).Count();
        }
        if (input.ContainsKey("Permissions") && input.GetValueOrDefault("Permissions") is List<string> userPermissions)
        {
            if (data != null)
            {
                data.Permissions = [.. userPermissions];
            }
        }
        return await Task.FromResult(new WorkflowOutput
        {
            Success = true,
            Data = data
        });
    }
}
